package com.screen.screendisplay.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.dryport.DryportProdoperTurnover;
import com.screen.screendisplay.mapper.dryport.DryportProdoperTurnoverMapper;
import com.screen.screendisplay.service.dryport.DryportProdoperTurnoverService;
import com.screen.screendisplay.vo.dryport.TurnoverVO;
import com.screen.screendisplay.vo.wholeproduct.GoodsTurnoverVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 周转计划情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportProdoperTurnoverServiceImpl extends ServiceImpl<DryportProdoperTurnoverMapper, DryportProdoperTurnover> implements DryportProdoperTurnoverService {

    @Override
    public List<TurnoverVO> getMonthlyStatsByYear(Integer year) {
        List<DryportProdoperTurnover> entityList;
        
        // 如果year为null，获取最新的月度数据；否则根据年份查询
        if (year == null) {
            entityList = baseMapper.getLatestMonthlyStats();
        } else {
            entityList = baseMapper.getMonthlyStatsByYear(year);
        }
        
        // 转换为VO对象
        return entityList.stream().map(entity -> {
            TurnoverVO vo = new TurnoverVO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<GoodsTurnoverVO> getGoodsTurnoverAnnual(Integer year) {
        List<GoodsTurnoverVO> resultList = new ArrayList<>();
        
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 查询最近5年的数据
        for (int i = 4; i >= 0; i--) {
            int targetYear = currentYear - i;
            
            // 查询目标年份的所有月份数据
            LambdaQueryWrapper<DryportProdoperTurnover> query = new LambdaQueryWrapper<>();
            query.eq(DryportProdoperTurnover::getYear, targetYear);
            
            // 如果是当前年份，只查询到当前月份
            if (targetYear == currentYear) {
                query.le(DryportProdoperTurnover::getMonth, currentMonth);
            }
            
            List<DryportProdoperTurnover> yearDataList = this.list(query);
            
            if (!yearDataList.isEmpty()) {
                GoodsTurnoverVO vo = new GoodsTurnoverVO();
                vo.setYear(targetYear);
                
                // 汇总年度计划量和完成量（累加各月数据）
                BigDecimal totalPlanned = yearDataList.stream()
                        .map(DryportProdoperTurnover::getTurnoverPlanned)
                        .filter(planned -> planned != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                BigDecimal totalCompleted = yearDataList.stream()
                        .map(DryportProdoperTurnover::getTurnoverCompleted)
                        .filter(completed -> completed != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                vo.setTurnoverPlanned(totalPlanned.setScale(2, RoundingMode.HALF_UP));
                vo.setTurnoverCompleted(totalCompleted.setScale(2, RoundingMode.HALF_UP));
                
                // 计算同比率：需要去年同期的完成量
                int lastYear = targetYear - 1;
                LambdaQueryWrapper<DryportProdoperTurnover> lastYearQuery = new LambdaQueryWrapper<>();
                lastYearQuery.eq(DryportProdoperTurnover::getYear, lastYear);
                
                // 如果是当前年份，去年也只查询到对应的月份
                if (targetYear == currentYear) {
                    lastYearQuery.le(DryportProdoperTurnover::getMonth, currentMonth);
                }
                
                List<DryportProdoperTurnover> lastYearDataList = this.list(lastYearQuery);
                
                if (!lastYearDataList.isEmpty()) {
                    BigDecimal lastYearCompleted = lastYearDataList.stream()
                            .map(DryportProdoperTurnover::getTurnoverCompleted)
                            .filter(completed -> completed != null)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    // 同比率(%) = (今年完成量 - 去年完成量) / 去年完成量 * 100
                    if (lastYearCompleted.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal yoyRate = totalCompleted.subtract(lastYearCompleted)
                                .divide(lastYearCompleted, 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal("100"))
                                .setScale(2, RoundingMode.HALF_UP);
                        vo.setYoyRate(yoyRate);
                    }
                }
                
                resultList.add(vo);
            }
        }
        
        return resultList;
    }

}
